var express = require('express')
var app = express();
var fs = require('fs')
var mysql=require('mysql')//mysql数据库
var http = require('http').createServer(app);
const multiparty = require('multiparty')
const body = require('body-parser')
app.use('/public', express.static('public'));
app.use(body.json());  //body-parser 解析json格式数据
app.use(body.urlencoded({            //此项必须在 bodyParser.json 下面,为参数编码
  extended: true
}));
const book=mysql.createConnection({//mysql的连接游标 连接书籍数据库
   host:"localhost",
   user:"root",
   password:"",
   database:"book"
})
book.connect();
const a=mysql.createConnection({//mysql的连接游标 连接用户数据库
  host:"localhost",
  user:"root",
  password:"",
  database:"a"
})
a.connect();
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "name,age,Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
});

app.post('/a', (req, res) => {
  console.log(req.body)
  res.json({
    name: req.body.name,
    age: req.body.age
  })
})
app.get('/search', (req, res) => {
  let sql = `SELECT name  FROM books`
  book.query(sql,(err, data) => {
    if (err) return
    res.json(data)
  })
})
app.post('/deng', (req, res) =>{
	let id = req.body.user
	let name = req.body.pass
	let sql = `SELECT amder  FROM admin WHERE  amder= ?`
	let sql1 = `SELECT pass  FROM admin WHERE amder = ?`
	a.query(sql,[id], (err, result) => {
		if(result.length === 0) {
			res.json({ok:500})
		} else {
			a.query(sql1,[id],(err, data) => {
				if(err) return 
				console.log(data[0])
				if (typeof data[0].pass === 'undefined')  {
					res.json({ok:500})
				} else {
					if (data[0].pass === name) {
						res.json({ok:200})
					} else {
						res.json({ok:404})
					}
				}
			})
		}
	})
})
app.post('/create', (req,res) => {
	console.log(req.body)
	let admin = {
		user: req.body.user || 1,
		pass: req.body.pass || 2
	}
	let id = admin.user
	let name = admin.pass
	let sql = `INSERT INTO admin(amder, pass) VALUES (?,?)`
	a.query(sql,[id,name],(err,data) => {
		if(err) return
		res.json({ok:200})
	})
	
})
app.get('/userinfo',(req, res) => {
	let query=()=>{
	        return new Promise((resolve,rejects)=>{
	            con.query("SELECT * FROM d",async function(err,res){
	                if(err) throw err;
	                resolve(res)              
	             })
	        })
	    }
	    async function uery(){
	       return await query()         
	    }
		console.log(uery())
		let user = uery()
		user.then(x=>{
			res.json(x)
		}).catch(err=>{
			res.json({status:404})
		})
})
app.get('/b', (req, res) => {
  console.log(req)
  res.json({
    name: req.query.name,
    age: req.query.age
  })
})
app.post("/info",  function (req, res) {
  /* 生成multiparty对象，并配置上传目标路径 */
  let form = new multiparty.Form();
  // 设置编码
  form.encoding = 'utf-8';
  // 设置文件存储路径，以当前编辑的文件为相对路径
  form.uploadDir = './public/';
  // 设置文件大小限制
  // form.maxFilesSize = 1 * 1024 * 1024;
  form.parse(req, function (err, fields, files) {
    try {
      let inputFile = files.fiie[0];
      let newPath = form.uploadDir  + inputFile.originalFilename;
      // 同步重命名文件名 fs.renameSync(oldPath, newPath)
　　　 //oldPath  不得作更改，使用默认上传路径就好
      fs.renameSync(inputFile.path, newPath);
      res.send({ data: "上传成功！" });
    } catch (err) {
      console.log(err);
      res.send({ err: "上传失败！" });
    };
  })
});
app.post('/send',async (req, res) => {
  function read () {
    return new Promise((resolve, rejects) => {
      fs.readFile('./public/2020.jpg',function(err, data) {
        resolve(data)
        rejects(err)
      })
    })
  }
  let data = await  read()
  res.send(data)
})
http.listen(3000, () => {
  console.log('listening on *:3000');
});